package edu.nf.takeoutdemo.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import edu.nf.takeoutdemo.commons.constant.StatusConstant;
import edu.nf.takeoutdemo.commons.enumeration.RedisKeyEnum;
import edu.nf.takeoutdemo.commons.result.PageResult;
import edu.nf.takeoutdemo.mapper.DishFlavorMapper;
import edu.nf.takeoutdemo.mapper.DishMapper;
import edu.nf.takeoutdemo.mapper.SetmealDishMapper;
import edu.nf.takeoutdemo.mapper.SetmealMapper;
import edu.nf.takeoutdemo.model.converter.DishConverter;
import edu.nf.takeoutdemo.model.dto.DishDTO;
import edu.nf.takeoutdemo.model.dto.DishPageQueryDTO;
import edu.nf.takeoutdemo.model.entity.Dish;
import edu.nf.takeoutdemo.model.entity.DishFlavor;
import edu.nf.takeoutdemo.model.entity.Setmeal;
import edu.nf.takeoutdemo.model.vo.DishVO;
import edu.nf.takeoutdemo.service.DishService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author zjl
 * @date 2025/10/25
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class DishServiceImpl implements DishService {
    private final DishMapper dishMapper;
    private final SetmealDishMapper setmealDishMapper;
    private final DishFlavorMapper dishFlavorMapper;
    private final DishConverter dishConverter;
    private final RedisTemplate<String,List<DishVO>>  redisTemplate;
    private final String key = RedisKeyEnum.DISH_CATEGORY.value();
    private final SetmealMapper setmealMapper;

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPageNum(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断当前菜品是否能够删除--是否存在起售中的菜品
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //当前菜品处于起售中，不能删除
                throw new RuntimeException("当前有菜品处于起售中，不能删除");
            }
        }
        //判断当前菜品是否能够删除--是否被套餐关联了
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds!=null && !setmealIds.isEmpty()) {
            //当前有菜品被套餐关联了，不能删除
            throw new RuntimeException("当前有菜品被套餐关联了，不能删除");
        }
        //根据菜品id集合批量删除菜品信息
        dishMapper.deleteByIds(ids);
        //根据菜品id集合批量删除关联的口味数据
        dishFlavorMapper.deleteByDishIds(ids);
        cleanCache(key+"*");
    }

    @Transactional
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        //给菜品表插入1条数据
        Dish dish = dishConverter.toDish(dishDTO);
        dishMapper.add(dish);

        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors!=null && !flavors.isEmpty()){
            flavors.forEach(flavor->{
                flavor.setDishId(dishId);
            });
            //给口味表插入n条数据
            dishFlavorMapper.addBatch(flavors);
        }
        redisTemplate.delete(key+dishDTO.getCategoryId());
    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //根据id查询菜品数据
        Dish dish = dishMapper.getById(id);
        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors =  dishFlavorMapper.getByDishId(id);
        //将查询到的数据封装到VO
        DishVO dishVO = dishConverter.toDishVO(dish);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    @Transactional
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = dishConverter.toDish(dishDTO);
        //修改菜品表基本信息
        dishMapper.update(dish);
        //删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors!=null && !flavors.isEmpty()){
            flavors.forEach(flavor->{
                flavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.addBatch(flavors);
        }
        cleanCache(key+"*");
    }

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<DishVO> dishVOList = new ArrayList<>();
        if(!redisTemplate.hasKey(key+dish.getCategoryId())){
            List<Dish> dishList = dishMapper.list(dish);
            for (Dish d : dishList) {
                DishVO dishVO = dishConverter.toDishVO(d);
                List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
                dishVO.setFlavors(flavors);
                dishVOList.add(dishVO);
            }
            //缓存一天
            redisTemplate.opsForValue().set(key+dish.getCategoryId(),dishVOList,24, TimeUnit.HOURS);
        }
        List<DishVO> list = redisTemplate.opsForValue().get(key+dish.getCategoryId());
        return list;
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);
        List<Dish> list = dishMapper.list(dish);
        return list;
    }

    @Transactional
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.update(dish);
        if (StatusConstant.DISABLE.equals(status)) {
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds!=null && !setmealIds.isEmpty()) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = new Setmeal();
                    setmeal.setId(setmealId);
                    setmeal.setStatus(StatusConstant.DISABLE);
                    setmealMapper.update(setmeal);
                }
            }
        }
        cleanCache(key+"*");
    }

    @Override
    public DishVO getDish(Long id) {
        Dish dish = dishMapper.getById(id);
        DishVO dishVO = dishConverter.toDishVO(dish);
        return dishVO;
    }

    /**
     * 清除缓存
     * @param patten
     */
    private void cleanCache(String patten) {
        Set<String> keys = redisTemplate.keys(patten);
        redisTemplate.delete(keys);
    }
}
